package com.freestyle.seatabusiness.authorization.config;

import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.csp.sentinel.log.RecordLog;
import com.alibaba.csp.sentinel.property.PropertyListener;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.freestyle.common.JsonUtils;
import com.freestyle.easyshiro.EasyShiroProperties;
import com.freestyle.easyshiro.intercept.method.config.EasyShiroMethodProperties;
import io.netty.util.concurrent.CompleteFuture;
import lombok.Getter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * Created by rocklee on 2022/4/7 9:18
 */
@Configuration
@Slf4j
@Getter
//@RefreshScope
//@ConfigurationProperties(prefix = "easy-shiro")
public class AuthenConfig  {
  @Value("${spring.cloud.nacos.discovery.server-addr}")
  private String nacosAddrs;
  private String groupId="my-seta-business";
  private String dataId="my-seta-business:authen-Config";
  @Resource
  protected EasyShiroMethodProperties properties;
  @PostConstruct
  public void init(){
    ReadableDataSource<String, EasyShiroMethodProperties> nacosDataSource = new NacosDataSource<>(nacosAddrs, groupId, dataId,
            source -> JsonUtils.fromJson(source, new TypeReference<>() {
            }));
    synchronized (nacosDataSource.getProperty()) {
      nacosDataSource.getProperty().addListener(new PropertyListener(){
        private void updateLocal(Object value){
          BeanUtils.copyProperties(value,properties);
        }
        @Override
        public void configUpdate(Object value) { //nacos的配置更新时触发
           log.info("configUpdate:"+value);
           updateLocal(value);
        }

        @Override
        public void configLoad(Object value) {//第一次下载nacos配置时触发
          log.info("configLoad:"+value);
          updateLocal(value);
        }
      });
    }
    //FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
  }


}
